<template>
  <div class="register-container">
    <div class="register-wrapper">
      <h2 class="register-title">找回密码</h2>
      
      <!-- 步骤指示器 -->
      <div class="step-indicator">
        <!-- :class="{ active: currentStep === 1, completed: currentStep > 1 }"
         这句话是给我的容器在满足一定的条件下添加样式 -->
        <div class="step-item" :class="{ active: currentStep === 1, completed: currentStep > 1 }">
          <div class="step-number">{{ currentStep > 1 ? '✓' : '1' }}</div>
          <div class="step-text">验证身份</div>
        </div>
        <div class="step-line" :class="{ active: currentStep > 1 }"></div>
        <div class="step-item" :class="{ active: currentStep === 2, completed: currentStep > 2 }">
          <div class="step-number">{{ currentStep > 2 ? '✓' : '2' }}</div>
          <div class="step-text">设置新密码</div>
        </div>
        <div class="step-line" :class="{ active: currentStep > 2 }"></div>
        <div class="step-item" :class="{ active: currentStep === 3 }">
          <div class="step-number">3</div>
          <div class="step-text">重置成功</div>
        </div>
      </div>

      <!-- 步骤1：验证手机号 -->
      <div v-if="currentStep === 1" class="step-content">
        <el-form ref="phoneFormRef" :model="phoneForm" :rules="phoneRules" class="register-form">
          <!-- 手机号输入框 -->
          <el-form-item prop="phone" class="form-item-wrapper">
            <div class="phone-input-wrapper">
              <div class="country-code-container">
                <span class="country-code">中国 0086</span>
              </div>
              <el-input
                v-model="phoneForm.phone"
                placeholder="输入注册使用的手机号"
                :prefix-icon="Phone"
              />
            </div>
          </el-form-item>

          <el-form-item class="form-item-wrapper">
            <div class="verification-wrapper">
              <el-input
                v-model="phoneForm.verificationCode"
                placeholder="请输入验证码"
                :prefix-icon="Key"
              />
              <el-button
                type="primary"
                :disabled="isSending || countdown > 0"
                @click="sendVerificationCode"
                class="send-code-btn"
              >
                {{ countdown > 0 ? `${countdown}秒后重试` : '获取验证码' }}
              </el-button>
            </div>
          </el-form-item>

          <el-form-item class="form-item-wrapper">
            <el-button
              type="primary"
              class="next-step-btn"
              :loading="isSubmitting"
              @click="nextToStep2"
              :disabled="!phoneForm.phone || !phoneForm.verificationCode"
            >
              继续
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 步骤2：设置新密码 -->
      <div v-if="currentStep === 2" class="step-content">
        <el-form ref="passwordFormRef" :model="passwordForm" :rules="passwordRules" class="register-form">
          <!-- 新密码输入框 -->
          <el-form-item prop="newPassword" class="form-item-wrapper">
            <el-input
              v-model="passwordForm.newPassword"
              type="password"
              placeholder="8-16位字母和数字组合"
              :prefix-icon="Lock"
              show-password
            />
          </el-form-item>

          <!-- 确认新密码输入框 -->
          <el-form-item prop="confirmPassword" class="form-item-wrapper">
            <el-input
              v-model="passwordForm.confirmPassword"
              type="password"
              placeholder="请再次输入新密码"
              :prefix-icon="Lock"
              show-password
            />
          </el-form-item>

          <el-form-item class="form-item-wrapper">
            <el-button
              type="primary"
              class="register-btn"
              :loading="isSubmitting"
              @click="submitNewPassword"
              :disabled="!canSubmit"
            >
              确认修改
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 步骤3：重置成功 -->
      <div v-if="currentStep === 3" class="step-content">
        <div class="success-container">
          <div class="success-icon">✓</div>
          <h3 class="success-title">密码重置成功</h3>
          <p class="success-message">
            恭喜您，密码已成功重置！<br />
            <span>{{ redirectCountdown }}秒后将自动跳转到登录页面...</span>
          </p>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onUnmounted } from 'vue';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
import { post,  type RequestConfig } from '@/utils/request';
import { Lock, Phone, Key } from '@element-plus/icons-vue';


// 路由实例
const router = useRouter();

// 步骤控制
const currentStep = ref(1);
const redirectCountdown = ref(3);
let countdownTimer: number | null = null;

// 表单引用
const phoneFormRef = ref<any>();
const passwordFormRef = ref<any>();

// 步骤1：手机号表单数据
const phoneForm = reactive({
  phone: '',
  verificationCode: ''
});

// 步骤2：密码表单数据
const passwordForm = reactive({
  newPassword: '',
  confirmPassword: ''
});

// 验证状态和错误信息
const isPhoneValid = ref(false);
const isSending = ref(false);
const countdown = ref(0);
const isSubmitting = ref(false);


// 密码验证函数
const validatePassword = (rule: any, value: string, callback: any) => {
  if (!value) {
    callback(new Error('密码不能为空'));
  } else if (value.length < 8 || value.length > 16) {
    callback(new Error('密码长度为8-16位'));
  } else {
    const hasNumber = /\d/.test(value);
    const hasLetter = /[a-zA-Z]/.test(value);
    if (!hasNumber || !hasLetter) {
      callback(new Error('密码必须同时包含数字和字母'));
    } else {
      callback();
      // 验证密码后，同时验证确认密码
      if (passwordForm.confirmPassword) {
        validateConfirmPassword({ field: 'confirmPassword' }, passwordForm.confirmPassword, () => {});
      }
    }
  }
};

// 确认密码验证函数
const validateConfirmPassword = (rule: any, value: string, callback: any) => {
  if (!value) {
    callback(new Error('请确认密码'));
  } else if (value !== passwordForm.newPassword) {
    callback(new Error('两次输入的密码不一致'));
  } else {
    callback();
  }
};

// 手机号验证函数
const validatePhone = (rule: any, value: string, callback: any) => {
  if (!value) {
    callback(new Error('请输入手机号'));
  } else if (!/^1[3-9]\d{9}$/.test(value)) {
    callback(new Error('请输入正确的手机号码'));
  } else {
    isPhoneValid.value = true;
    callback();
  }
};

// 手机号验证规则
const phoneRules = {
  phone: [
    { validator: validatePhone, trigger: 'blur' }
  ]
};

// 密码验证规则
const passwordRules = {
  newPassword: [
    { validator: validatePassword, trigger: 'blur' }
  ],
  confirmPassword: [
    { validator: validateConfirmPassword, trigger: 'blur' }
  ]
};

// 计算是否可以提交重置
const canSubmit = computed(() => {
  return passwordForm.newPassword && 
         passwordForm.confirmPassword
});


// 发送验证码（找回密码专用）
const sendVerificationCode = async () => {
  isPhoneValid.value = await phoneFormRef.value.validate();
  if (!isPhoneValid.value) {
    ElMessage.warning('请输入正确的手机号码');
    return;
  }

  isSending.value = true;
  try {
    // 调用后端发送验证码接口（找回密码专用）
    await post('/forgot/sendCode', {
      phone: phoneForm.phone
    },{ showLoading: false } as RequestConfig);
    startCountdown();
  } catch (error) {
    console.error('Send verification code error:', error);
  } finally {
    isSending.value = false;
  }
};

// 开始倒计时
const startCountdown = () => {
  countdown.value = 120;
  const timer = setInterval(() => {
    countdown.value--;
    if (countdown.value <= 0) {
      clearInterval(timer);
    }
  }, 1000);
};

// 下一步：验证手机后进入设置密码
const nextToStep2 = async () => {
  if (!phoneFormRef.value) return;
  
  const valid = await phoneFormRef.value.validate();
  if (valid) {
    isSubmitting.value = true;
    try {
      // 调用后端验证验证码接口（找回密码专用）
      await post('/forgot/verifyCode', {
        phone: phoneForm.phone,
        code: phoneForm.verificationCode
      });
      currentStep.value = 2;
    } catch (error) {
      console.error('Verify phone code error:', error);
    } finally {
      isSubmitting.value = false;
    }
  }
};

// 提交新密码
const submitNewPassword = async () => {
  if (!passwordFormRef.value) return;
  
  const valid = await passwordFormRef.value.validate();
  if (valid && canSubmit.value) {
    isSubmitting.value = true;
    try {
      // 调用后端重置密码接口
      await post('/forgot/resetPwd', {
        phone: phoneForm.phone,
        newPwd: passwordForm.newPassword
      });
      // 重置成功，进入第三步
      currentStep.value = 3;
      startRedirectCountdown();
    } catch (error) {
      console.error('Reset password error:', error);
    } finally {
      isSubmitting.value = false;
    }
  }
};

// 开始跳转倒计时
const startRedirectCountdown = () => {
  redirectCountdown.value = 3;
  countdownTimer = window.setInterval(() => {
    redirectCountdown.value--;
    if (redirectCountdown.value <= 0) {
      redirectToLogin();
    }
  }, 1000);
};

// 跳转到登录页
const redirectToLogin = () => {
  if (countdownTimer) {
    clearInterval(countdownTimer);
  }
  router.replace('/login');
};

// 清理定时器
onUnmounted(() => {
  if (countdownTimer) {
    clearInterval(countdownTimer);
  }
});
</script>

<style scoped>

/* 主要布局调整 */
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f7fa;
  padding: 20px;
}

.register-wrapper {
  width: 100%;
  max-width: 750px;
  background-color: #fff;
  padding: 50px;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.register-title {
  text-align: center;
  margin-bottom: 40px;
  color: #303133;
  font-size: 28px;
  font-weight: 600;
}

/* 步骤指示器样式 */
.step-indicator {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 50px;
  padding: 0 30px;
}

.step-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  flex: 1;
}

.step-number {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: #dcdfe6;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 600;
  margin-bottom: 12px;
  transition: all 0.3s;
  font-size: 16px;
}

.step-text {
  font-size: 16px;
  color: #909399;
  transition: color 0.3s;
}

.step-item.active .step-number {
  background-color: #409eff;
  color: #fff;
}

.step-item.active .step-text {
  color: #409eff;
  font-weight: 500;
}

.step-item.completed .step-number {
  background-color: #67c23a;
  color: #fff;
}

.step-item.completed .step-text {
  color: #67c23a;
}

.step-line {
  flex: 1;
  height: 3px;
  background-color: #dcdfe6;
  margin: 0 15px;
  transition: background-color 0.3s;
}

.step-line.active {
  background-color: #409eff;
}

/* 表单样式 */
.register-form {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
}

/* 统一表单项容器样式 - 相对定位，为错误提示的绝对定位做准备 */
.form-item-wrapper {
  width: 450px;
  margin-bottom: 28px;
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
  min-height: 80px; /* 确保表单项高度稳定，包含错误信息空间 */
}

/* 手机号输入框容器 */
.phone-input-wrapper {
  display: flex;
  height: 60px;
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  overflow: hidden;
  background-color: #fff;
  width: 100%;
  max-width: 620px;
  transition: border-color 0.3s;
}

/* 确保手机号输入框和验证码区域长度完全一致 */
.phone-input-wrapper,
.verification-wrapper {
  width: 100%;
  max-width: 620px;
}

/* 调整国家代码容器宽度 */
.country-code-container {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 120px;
  padding: 0 15px;
  background-color: #f5f7fa;
  border-right: 1px solid #dcdfe6;
  height: 100%;
}

.country-code {
  color: #606266;
  font-size: 16px;
  font-weight: 500;
}

/* 验证码区域样式 */
.verification-wrapper {
  display: flex;
  gap: 15px;
  align-items: center;
  width: 100%;
  max-width: 620px;
}

/* 图标样式调整 */
:deep(.el-input__prefix) {
  display: flex;
  align-items: center;
  justify-content: center;
  left: 15px;
  color: #909399;
  height: 100%;
}

:deep(.el-input__prefix-inner) {
  display: flex;
  align-items: center;
  justify-content: center;
}

:deep(.el-input__prefix .el-icon) {
  font-size: 20px;
}

/* 调整输入框内边距和字体大小 */
:deep(.el-input__inner) {
  padding-left: 50px;
  padding-right: 50px;
  font-size: 18px;
}

/* 按钮样式 */
.send-code-btn {
  width: 140px;
  height: 60px;
  font-size: 18px;
  border-radius: 6px;
}

.next-step-btn,
.register-btn {
  width: 300px;
  max-width: 620px;
  height: 60px;
  font-size: 20px;
  background-color: #ff6700;
  border-color: #ff6700;
  margin-top: 15px;
  border-radius: 6px;
  font-weight: 500;
}

.next-step-btn:hover,
.register-btn:hover {
  background-color: #ff7a23;
  border-color: #ff7a23;
}

/* 聚焦效果 */
.phone-input-wrapper:focus-within {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

:deep(.el-input__wrapper:focus-within) {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

/* 确保所有步骤内容居中 */
.step-content {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  width: 100%;
}

/* 成功页面样式 */
.success-container {
  text-align: center;
  padding: 80px 0;
}

.success-icon {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  background-color: #67c23a;
  color: #fff;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  font-size: 64px;
  font-weight: bold;
  margin-bottom: 30px;
}

.success-title {
  font-size: 32px;
  color: #303133;
  margin-bottom: 25px;
}

.success-message {
  font-size: 18px;
  color: #606266;
  line-height: 1.8;
}

.success-message span {
  color: #409eff;
}

/* 错误状态样式 - 确保错误状态优先级高于聚焦状态 */
.el-form-item.is-error .phone-input-wrapper {
  border-color: #f56c6c !important;
  box-shadow: 0 0 0 2px rgba(245, 108, 108, 0.2) !important;
}

.el-form-item.is-error .country-code-container {
  border-color: #f56c6c !important;
}

:deep(.el-form-item.is-error .el-input__wrapper) {
  border-color: #f56c6c !important;
  box-shadow: 0 0 0 2px rgba(245, 108, 108, 0.2) !important;
  height: 60px !important;
  min-height: 60px !important;
}

/* 确保错误状态下聚焦时不显示蓝色 */
.el-form-item.is-error .phone-input-wrapper:focus-within {
  border-color: #f56c6c !important;
  box-shadow: 0 0 0 2px rgba(245, 108, 108, 0.2) !important;
}

:deep(.el-form-item.is-error .el-input__wrapper:focus-within) {
  border-color: #f56c6c !important;
  box-shadow: 0 0 0 2px rgba(245, 108, 108, 0.2) !important;
}

/* 确保错误状态下输入框大小不变的关键样式 */
:deep(.el-input) {
  height: 60px !important;
  min-height: 60px !important;
  box-sizing: border-box !important;
}

:deep(.el-input__wrapper) {
  height: 60px !important;
  min-height: 60px !important;
  box-sizing: border-box !important;
}

:deep(.el-input__inner) {
  height: 100% !important;
  box-sizing: border-box !important;
}

/* 确保小眼睛图标显示的样式 */
:deep(.el-icon-view) {
  display: inline-block;
}
</style>